# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Tellstick
  #Validates and converts code string to a positive integer
  #Uses an array patters to validate code against
  class CodeConverter
    def initialize(patterns,integer_offset=0)
      @patterns = patterns
      @integer_offset = integer_offset
    end
    
    def to_i(code)
      choices = %w{integer_str upcase_str lowcase_str}
      self.class.send(choices[find_parser(code)],code,@integer_offset)
    end

    private
    def find_parser(code)
      @patterns.each_with_index do |pattern,index|
        result = self.class.match_code(code,pattern,index)
        return result unless result == nil
      end
    end

    def self.match_code(code,pattern,index)
      return index if ((code =~ pattern) == 0)
      nil
    end

    def self.integer_str(*args)
      args[0].to_i + args[1]
    end

    def self.upcase_str(*args)
      args[0][0]-"A"[0]
    end

    def self.lowcase_str(*args)
      args[0][0]-"a"[0]
    end
  end
end